package com.hospicpc.demos.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

public class JwtUtil {
    private static final String secretKey = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9"; //进行数字签名的私钥，一定要保管好


    /**
     *生成串
     * @param token
     * @param id
     * @param account
     * @return
     * @throws Exception
     */
    public static String getJWT(Map<String,Object> m,Long millis)  {
        //生成jwt令牌
        JwtBuilder jwtBuilder = Jwts.builder()
                // .setId(id)//设置jwt
                // .setSubject("测试")//设置jwt主题
                .setIssuedAt(new Date())//设置jwt签发日期
                .setExpiration(new Date(System.currentTimeMillis()+millis))//设置jwt的过期时间
                .setClaims(m)
                .signWith(SignatureAlgorithm.HS256, secretKey);
        return jwtBuilder.compact();
    }

    /**
     * 解析JWT字符串
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) {
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }


    public static Integer getUserIdByJWT(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader("Authorization");
        //jwt解析token,获取用户信息
        try {
            Claims claims = JwtUtil.parseJWT(token);
            Integer id = (Integer) claims.get("id");
            return id;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}

